package com.bnlr.lrparking.appui.publish.my;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bnlr.lrparking.constant.LrConstant;
import com.bnlr.lrparking.constant.Urls;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.bnlr.lrparking.app.Application;
import com.bnlr.lrparking.R;
import com.bnlr.lrparking.appui.stall.StallBegRentBuy;
import com.bnlr.lrparking.appui.stall.StallDealDetailActivity;
import com.bnlr.lrparking.base.BaseActivity;
import com.bnlr.lrparking.app.AppConfig;
import com.bnlr.lrparking.model.BaseArrayBean;
import com.bnlr.lrparking.model.MyPublishBean;
import com.bnlr.lrparking.appui.publish.PublishActivity;
import com.bnlr.lrparking.appui.publish.adapter.SelectPublishAdapter;
import com.bnlr.lrparking.view.CarCommon;
import com.bnlr.lrparking.widget.refresh.RefreshHolderUtil;
import com.bnlr.lrparking.widget.refresh.XRefreshLayout;
import com.bnlr.nohttp.CallServer;
import com.bnlr.nohttp.CustomHttpListener;
import com.yolanda.nohttp.NoHttp;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

public class SelectMyPublishActivity extends BaseActivity {
    @BindView(R.id.tv_nav_title)
    TextView tvNavTitle;
    @BindView(R.id.rv_match_stall)
    RecyclerView rvMatchStall;
    @BindView(R.id.xrefresh_match_stall)
    XRefreshLayout xrefreshMatchStall;
    private Unbinder unbinder;
    private List<MyPublishBean.DataBean> dataList = new ArrayList<>();
    private int currentPage = 1;
    private SelectPublishAdapter adapter;
    private int requestType;
    private int stallId;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_select_my_publish);
        unbinder = ButterKnife.bind(this);
        tvNavTitle.setText("我的发布");
        int type = getIntent().getIntExtra("select_publish_type",20);
        stallId = getIntent().getIntExtra("submit_stall_id",0);
        if (type == 20) {
            requestType = 10;
        } else {
            requestType = 11;
        }
        initView();

    }

    private void initView() {
        rvMatchStall.setLayoutManager(new LinearLayoutManager(this));
        rvMatchStall.setItemAnimator(new DefaultItemAnimator());
        xrefreshMatchStall.setRefreshViewHolder(RefreshHolderUtil.getRefreshHolder(this));
        xrefreshMatchStall.setDelegate(new XRefreshLayout.BGARefreshLayoutDelegate() {
            @Override
            public void onBGARefreshLayoutBeginRefreshing(XRefreshLayout refreshLayout) {
                currentPage = 1;
                getMatchStall(currentPage);
            }

            @Override
            public boolean onBGARefreshLayoutBeginLoadingMore(XRefreshLayout refreshLayout) {
                return false;
            }

        });
        adapter = new SelectPublishAdapter(dataList);
        rvMatchStall.setAdapter(adapter);
        //adapter.setLoadMoreView(new CustomPublishLoadMoreView());
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                MyPublishBean.DataBean md = dataList.get(position);
                if (LrConstant.BEG_RENT == md.getType() || LrConstant.BEG_SELL == md.getType()) {
                    Intent intent = new Intent(SelectMyPublishActivity.this, StallBegRentBuy.class);
                    intent.putExtra("stall_id", md.getId());
                    intent.putExtra("is_waiting", true);
                    startActivity(intent);
                } else {
                    Intent intent = new Intent(SelectMyPublishActivity.this, StallDealDetailActivity.class);
                    intent.putExtra("stall_id", md.getId());
                    intent.putExtra("is_waiting", true);
                    startActivity(intent);
                }
            }
        });
        adapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                //  上拉加载
                currentPage++;
                getMatchStall(currentPage);
            }
        },rvMatchStall);
    }

    @Override
    protected void onResume() {
        super.onResume();
        currentPage = 1;
        getMatchStall(currentPage);
    }

    private void getMatchStall(final int page) {
        try {
            mRequest = NoHttp.createStringRequest(Urls.SPACE_IP, LrConstant.POST);
            mRequest.add("action", "GetUserUsableSpace");
            mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));
            mRequest.add("phonePara", Application.DEVICE_ID);
            mRequest.add("pageIndex", page);
            mRequest.add("type",requestType);
            // 添加到请求队列+
            CallServer.getRequestInstance().add(this, mRequest,
                    new CustomHttpListener<MyPublishBean>(this, true, MyPublishBean.class) {
                        @Override
                        public void doWork(MyPublishBean data, String code) {
                            if (TextUtils.equals("1", code)) {
                                if (adapter != null) {
                                    if (data != null && data.getData().size() != 0) {
                                        if (page == 1) {
                                            dataList.clear();
                                            dataList = data.getData();
                                            adapter.setNewData(dataList);
                                        } else {
                                            dataList.addAll(dataList);
                                            adapter.notifyDataSetChanged();
                                        }
                                        adapter.loadMoreComplete();
                                    } else {
                                        if (page == 1) {
                                            dataList.clear();
                                            adapter.notifyDataSetChanged();
                                        } else {
                                            adapter.loadMoreEnd(true);
                                        }
                                    }
                                }
                            } else {
                                ToastUtils.showShort(data.getMsg()+"");
                            }
                        }
                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {
                            if (xrefreshMatchStall != null) {
                                xrefreshMatchStall.endRefreshing();
                            }
                        }
                    }, false);
        } catch (Exception e) {
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
    }

    @OnClick({R.id.add_match_stall, R.id.submit_match_stall})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.add_match_stall:
                if (requestType == 10 ) {
                    startActivity(new Intent(this, PublishActivity.class).putExtra("publish_tag",1));
                } else {
                    startActivity(new Intent(this, PublishActivity.class).putExtra("publish_tag",2));
                }
                break;
            case R.id.submit_match_stall:
                if (adapter.getSelectId().size() <= 0) {
                    ToastUtils.showShort("请选择要匹配的车位");
                    return;
                }
                String arrId = adapter.getSelectId().toString();
                LogUtils.e("arrId:" + arrId);
                arrId = arrId.substring(1,arrId.length()-1).trim();
                LogUtils.e("arrId:" + arrId);
                submitIntent(arrId);
                break;
            default:
                break;
        }
    }

    private void submitIntent(String arrId) {
        try {
            mRequest = NoHttp.createStringRequest(Urls.SPACE_IP, LrConstant.POST);
            mRequest.add("action", "SubmitMatchingSpace");
            mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));
            mRequest.add("phonePara", Application.DEVICE_ID);
            mRequest.add("sourceSpaceId",stallId);
            mRequest.add("tagetSpaceIdArr",arrId);
            LogUtils.e(Application.DEVICE_ID+"----" +stallId +" ---" +arrId);
            // 添加到请求队列+
            CallServer.getRequestInstance().add(this, mRequest,
                    new CustomHttpListener<BaseArrayBean>(this, true, BaseArrayBean.class) {
                        @Override
                        public void doWork(BaseArrayBean data, String code) {
                            if (TextUtils.equals("1", code)) {
                                CarCommon carCommon = new CarCommon();
                                carCommon.setClickSureListener(new CarCommon.ClickSureListener() {
                                    @Override
                                    public void setSure() {
                                        finish();
                                    }
                                });
                                carCommon.ReminderDialog(SelectMyPublishActivity.this,"已将您发布的车位信息发送给该用户，请您保持电话畅通。","提交成功");
                            }
                        }
                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {
                            if (!code.equals("1")) {
                                try {
                                    ToastUtils.showShort(obj.getString("msg"));
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }, true);
        } catch (Exception e) {
        }
    }
}
